package com.wpam.scrabble.mobile.activities;

import java.util.ArrayList;

import android.app.Activity;
import android.app.AlertDialog.Builder;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.ColorMatrix;
import android.graphics.ColorMatrixColorFilter;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.wpam.scrabble.mobile.GameResources;
import com.wpam.scrabble.mobile.R;
import com.wpam.scrabble.mobile.communication.CommunicationManager;
import com.wpam.scrabble.mobile.communication.bt.BluetoothManager;

public class PlayersWaitingActivity extends Activity implements OnClickListener {
	
	private UserAdapter adapter_;
	private Button startButton_;
	private BluetoothManager btManager_;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
    	
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_players_waiting);
        
        startButton_ = (Button) findViewById(R.id.startButton);
        CommunicationManager.getInstance(this);
        btManager_ = BluetoothManager.getInstance(this);
        
        if (adapter_ == null) {
        	adapter_ = new UserAdapter();
            ListView usersList = (ListView) findViewById(R.id.usersList);
        	usersList.setAdapter(adapter_);
        }
        
        if (!btManager_.isBtAvailable()) {
        	Toast.makeText(this, getResources().getString(R.string.device_does_not_support_bt), Toast.LENGTH_SHORT).show();
        	finish();
        }

        IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_ACL_DISCONNECTED);
        this.registerReceiver(mReceiver_, filter);
        startButton_.setOnClickListener(this);
        
		btManager_.setDiscoverable(300);
    }

	@Override
	public void onBackPressed() {
		
		CommunicationManager.getInstance(this).stopNetworkActions();
		CommunicationManager.disconnectAllClients();
		super.onBackPressed();
	}

	@Override
	protected void onDestroy() {

		this.unregisterReceiver(mReceiver_);
		super.onDestroy();
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		
		super.onActivityResult(requestCode, resultCode, data);
		btManager_.onActivityResult(requestCode, resultCode, data);
	}

	public class UserAdapter extends ArrayAdapter<PlayerInfo> {

    	private int[] colors = new int[] { getResources().getInteger(R.color.FirstRow), getResources().getInteger(R.color.SecondRow) };

		public UserAdapter() {
    		super(PlayersWaitingActivity.this, R.layout.user_row);
    	}
    	
    	@Override
		public void add(PlayerInfo object) {

    		if (getPosition(object) == -1) {
    			super.add(object);
    			notifyDataSetChanged();
    		}
		}
    	
    	public void remove(BluetoothDevice device) {
    		
    		super.remove(new PlayerInfo(device));
    		notifyDataSetChanged();
    	}
    	
    	@Override
    	public View getView(int position, View convertView, ViewGroup parent) {
    		
    		View row = null;
    		LayoutInflater inflater = getLayoutInflater();
    		
    		row = inflater.inflate(R.layout.user_row, parent, false);
    		
    		TextView name = (TextView) row.findViewById(R.id.userName);
    		ImageView readyImg = (ImageView) row.findViewById(R.id.readyImage);
    		ImageView acceptImg = (ImageView) row.findViewById(R.id.acceptImage);
    		ImageView rejectImg = (ImageView) row.findViewById(R.id.rejectImage);

    		acceptImg.setTag(getItem(position));
    		rejectImg.setTag(getItem(position));
    		
    		name.setText(getItem(position).getName());
    		
    		ColorMatrix matrix = new ColorMatrix();
    		matrix.setSaturation(0);
    		ColorMatrixColorFilter filter = new ColorMatrixColorFilter(matrix);
    		
    		if (getItem(position).isAccepted()) {
    			rejectImg.setColorFilter(filter);
        		rejectImg.setOnClickListener(new OnClickListener() {
    				
    				public void onClick(final View v) {
    					synchronized (this) {
    						((PlayerInfo)v.getTag()).setAccepted(false);
    						notifyDataSetChanged();
    					}
    				}
    			});
    		} else {
    			acceptImg.setColorFilter(filter);
        		acceptImg.setOnClickListener(new OnClickListener() {
    				
    				public void onClick(final View v) {
    					synchronized (this) {
    						((PlayerInfo)v.getTag()).setAccepted(true);
    						notifyDataSetChanged();
    					}
    				}
    			});
    		}
    		
    		if (getItem(position).isReady()) {
    			readyImg.setImageDrawable(getResources().getDrawable(R.drawable.ready));
    		} else {
    			readyImg.setImageDrawable(getResources().getDrawable(R.drawable.notready));
    		}
    		
    		int colorPos = position % colors.length;
    		row.setBackgroundColor(colors[colorPos]);
    		return row;
    	}
    }

	public UserAdapter getUserAdapter() {
		return adapter_;
	}
	
	public void addUserToList(final PlayerInfo pInfo) {
		
		runOnUiThread(new Runnable() {
			
			public void run() {

				adapter_.add(pInfo);
				adapter_.notifyDataSetChanged();
			}
		});
	}
	
	private final BroadcastReceiver mReceiver_ = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			
            String action = intent.getAction();
            if (BluetoothDevice.ACTION_ACL_DISCONNECTED.equals(action)) {
    			synchronized(adapter_) {
    				BluetoothDevice device = (BluetoothDevice)intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
    				BluetoothManager.getInstance().removeFromConnectedClients(device);
    				adapter_.remove(device);
    				adapter_.notifyDataSetChanged();
    			}
            }
	    }
    };

	public void setUserReady(PlayerInfo playerInfo) {
		
		for (int i = 0; i < adapter_.getCount(); ++i) {
			if (adapter_.getItem(i).equals(playerInfo)) {
				adapter_.getItem(i).setReady(true);
				runOnUiThread(new Runnable() {
					
					public void run() {

						adapter_.notifyDataSetChanged();
					}
				});
			}
		}		
	}
	
	public void onClick(View v) {

		if (v.getId() == R.id.startButton) {
			GameResources.getInstance(getApplicationContext());
			final ArrayList<String> arr = new ArrayList<String>();
			for (int i = 0; i < adapter_.getCount(); ++i)
				if (adapter_.getItem(i) != null && adapter_.getItem(i).isAccepted() && adapter_.getItem(i).isReady())
					arr.add(adapter_.getItem(i).getName());
			arr.add(CommunicationManager.getMyName());
			
			Builder builder = new Builder(v.getContext());
			if (arr.size() == 1) {
				builder.setTitle(getResources().getString(R.string.error));
				builder.setMessage(getResources().getString(R.string.players_not_selected_or_unready));
				builder.setPositiveButton(getResources().getString(R.string.ok), new DialogInterface.OnClickListener() {
					
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
					}
				});
			} else if (adapter_.getCount() != arr.size() - 1) {
				builder.setTitle(getResources().getString(R.string.readyness));
				builder.setMessage(getResources().getString(R.string.unselected_players_warning));
				builder.setPositiveButton(getResources().getString(R.string.yes), new DialogInterface.OnClickListener() {
					
					public void onClick(DialogInterface dialog, int which) {
						startGame(arr);
						dialog.dismiss();
					}
				});
				builder.setNegativeButton(getResources().getString(R.string.no), new DialogInterface.OnClickListener() {
					
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
					}
				});
				builder.create().show();
			} else 
				startGame(arr);
		}
	}
	
	private void startGame(ArrayList<String> arr) {
		
		Intent boardIntent = new Intent(this, BoardActivity.class); 
		boardIntent.putExtra("PlayerNames", arr);
		startActivity(boardIntent);
		CommunicationManager.getInstance().stopAcceptorTask();
		finish();
	}
	
}
